/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package interfaz;

import clases.ClsContraladorEventos;
import clases.ClsDatabase;
import clases.ClsMetodos;
import clases.ClsValidacion;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JTable;

/**
 *
 * @author Usuario
 */
public class dlg_CategoriaInsumo extends javax.swing.JDialog {

    private ClsDatabase bd=new ClsDatabase();
    private ClsContraladorEventos contraladorEventos=new ClsContraladorEventos();
    private ClsMetodos metodos=new ClsMetodos();
    private JTable table;
    private dlgIndice dialog;
    private String id="-1";
    private boolean editarUpdate=false;
    /**
     * Creates new form dlg_CategoriaInsumo
     */
    public dlg_CategoriaInsumo(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    public dlg_CategoriaInsumo(java.awt.Frame parent, boolean modal,JDialog dialog,JTable tblCategoriaInsumo) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);//Centramos la ventana
        this.dialog=(dlgIndice) dialog;
        this.table=tblCategoriaInsumo;
        metodos._iconJDialog(this);
        Limpiar();
    }

    // <editor-fold desc="CATEGORIA DE INSUMO CODE">
    //CATEGORIA DE INSUMO
    public void Editar(){
        int fila=table.getSelectedRow();//Obtenemos la fila seleccionada
        if (fila != -1) {//Si no se a seleccionado alguna row de la Tabla hacer...
           Object[][] datos=bd.select("insumo_indice",
                    "idinsumo_indice,descripcion,estado",
                    "idinsumo_indice='"+table.getValueAt(fila, 0)+"' ");
            if (datos != null) {
                id=datos[0][0].toString();
                txtDescripcion.setText(datos[0][1].toString());
                txtDescripcion.setSelectionStart(0);
                txtDescripcion.setSelectionEnd(txtDescripcion.getText().length());
                editarUpdate=true;
                setVisible(true);
            } else {
                System.err.println("------------------------>ERROR NO PREVISTO<--------------------------------");
            }
        } else {
            javax.swing.JOptionPane.showMessageDialog(this, "Seleccione un Índice Unificado");
            dispose();
        }
    }

    public void Guardar(){
        String nombreString=txtDescripcion.getText().toString();
        boolean seRepite=true;
        if (editarUpdate) {//Si se presiona EDITAR, entonces el nombre se actualiza, no es un INSERT
            seRepite=false;
        }else{//Verificamos si se repite
            seRepite=bd.verif_repite("SELECT descripcion FROM insumo_indice WHERE descripcion='"+nombreString+"'");
        }
        if (!seRepite) {//Verificamos si se Repite el Nombre de Unidad
            if (ClsValidacion.tieneCamposVacios(pnlAgregarCategoria)) {
                JOptionPane.showMessageDialog(null, "Ingrese el nombre");
                return;
            }

            if (editarUpdate) {
                //UPDATE
                //Realizamos la consulta
                boolean seInserto=bd.update("insumo_indice",
                        "descripcion='"+nombreString+"',estado='A'",
                        "idinsumo_indice="+id);
                if (!seInserto) {
                    JOptionPane.showMessageDialog(null, "No se pudo Actualizar el Índice unificado");
                }
                editarUpdate=false;
            }else{
                //INSERT
                //Realizamos la consulta
                id=metodos.generarCodigollaves("SELECT idinsumo_indice FROM insumo_indice ORDER BY idinsumo_indice desc LIMIT 0,1 ", 2);
                boolean seInserto=bd.insert("insumo_indice",
                        "idinsumo_indice,descripcion,estado",
                        "'"+id +"','"+nombreString+"','A'");
                if (!seInserto) {
                    JOptionPane.showMessageDialog(null, "No se pudo crear el Índice unificado");
                }
            }
            dialog.iniciar();
            this.dispose();
        } else {
            JOptionPane.showMessageDialog(null, "Ya existe el nombre del Índice unificado");
            txtDescripcion.requestFocus();
            txtDescripcion.setSelectionStart(0);
            txtDescripcion.setSelectionEnd(txtDescripcion.getText().length());
        }
    }

    public void Cancelar(){
        this.dispose();
    }

    private void Limpiar(){
        txtDescripcion.setText("");
        txtDescripcion.requestFocus();
    }
    // </editor-fold>

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlAgregarCategoria = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel11 = new javax.swing.JLabel();
        txtDescripcion = new javax.swing.JTextField();
        btnGuardar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Datos de Índice Unificado");

        pnlAgregarCategoria.setBackground(new java.awt.Color(225, 235, 247));
        pnlAgregarCategoria.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel2.setOpaque(false);
        jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel11.setText("Nombre:");
        jPanel2.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(16, 39, -1, -1));

        txtDescripcion.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtDescripcionKeyTyped(evt);
            }
        });
        jPanel2.add(txtDescripcion, new org.netbeans.lib.awtextra.AbsoluteConstraints(68, 36, 320, -1));

        pnlAgregarCategoria.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, 430, 100));

        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });
        pnlAgregarCategoria.add(btnGuardar, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 136, 100, -1));

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });
        pnlAgregarCategoria.add(btnCancelar, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 132, 100, 31));

        jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/fondo_dialog.jpg"))); // NOI18N
        pnlAgregarCategoria.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 450, 180));

        getContentPane().add(pnlAgregarCategoria, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        Guardar();
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        Cancelar();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void txtDescripcionKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDescripcionKeyTyped
        contraladorEventos.cantidadMaximaCaracteresJTextField(evt, txtDescripcion, 200);
    }//GEN-LAST:event_txtDescripcionKeyTyped

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(dlg_CategoriaInsumo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(dlg_CategoriaInsumo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(dlg_CategoriaInsumo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(dlg_CategoriaInsumo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                dlg_CategoriaInsumo dialog = new dlg_CategoriaInsumo(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel pnlAgregarCategoria;
    private javax.swing.JTextField txtDescripcion;
    // End of variables declaration//GEN-END:variables
}
